package com.slkj.shilixiaoyuanapp.ui.user.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.api.InjectParam;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.entity.StudentAttendanceHisEntity;
import com.slkj.shilixiaoyuanapp.entity.parent.StudentCheckEntity;
import com.slkj.shilixiaoyuanapp.net.HttpConfig;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.util.TimeUtils;
import com.slkj.shilixiaoyuanapp.view.CustomStateText;
import com.slkj.shilixiaoyuanapp.view.DividerItemDecoration;
import com.slkj.shilixiaoyuanapp.view.StateLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


@ActivityInfo(layout = R.layout.students_check_activity,title = "历史记录")
public class StudentsCheckActivity extends BaseActivity {
    @InjectParam
    int  stuId;
    @BindView(R.id.calendarView)
    CalendarView mCalendarView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    BaseQuickAdapter adapter;
    List<StudentCheckEntity.ListBean> historyEntityList = new ArrayList<>();
    @BindView(R.id.layout_root)
    StateLayout stateLayout;
    @BindView(R.id.layout_state_two)
    StateLayout stateLayoutRecyc;
    @BindView(R.id.tv_brfoe_month)
    TextView tvBrfoeMonth;
    @BindView(R.id.tv_now_month)
    TextView tvNowMonth;
    @BindView(R.id.tv_next_month)
    TextView tvNextMonth;
    @BindView(R.id.tv_state_zc)
    TextView tvStateZc;
    @BindView(R.id.tv_state_qj)
    TextView tvStateQj;
    @BindView(R.id.tv_state_yc)
    TextView tvStateYc;
    //日历标记数据缓存
    Map<String, List<Calendar>> calendarCache = new HashMap<>();
    //打卡历史缓存
    Map<String, StudentCheckEntity.ListBean> historyCache = new HashMap<>();
    //网络数据缓存
    Map<String, StudentCheckEntity> cache = new HashMap<>();

    //当前月份
    String nowMonth;

    //当前天
    String nowDay;

    @Override
    protected void init() {
        StudentsCheckActivity__JumpCenter.bind(this);
        nowMonth = TimeUtils.getNy();
        stateLayout.setOnReLoadListener(this::getFirstData);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BaseQuickAdapter<StudentCheckEntity.ListBean, BaseViewHolder>(R.layout.item_tool_xskq_history, historyEntityList) {
            @Override
            protected void convert(BaseViewHolder helper, final StudentCheckEntity.ListBean item) {
//                helper.setText(R.id.tv_grade,item.getYearClass())
//                        .setText(R.id.tv_fraction, GradeAdapter.getScoreStr(item.getScore()))
//                        .setVisible(R.id.img_first,helper.getAdapterPosition() == 0);
                helper.setText(R.id.tv_name, item.getName())
                        .setText(R.id.tv_type,item.getTypeStr());
                CustomStateText customStateText = helper.getView(R.id.view_state);
                customStateText.setSolidColor(item.getTypeColor());
            }
        };
        recyclerView.setAdapter(adapter);

        //设置日历选择监听
        mCalendarView.setOnDateSelectedListener((calendar, isClick) -> {
            nowDay = TimeUtils.getStrByNyr(calendar.getYear(), calendar.getMonth(), calendar.getDay());
            showDayDate(nowDay);
        });
        mCalendarView.setOnMonthChangeListener((year, month) -> {
            /**
             * 月份改变，进行操作
             * 1：修改统计数量
             * 2：查找缓存数据，是否请求网络
             * 3：更新日历标记视图
             * 4：确定显示哪一天的数据
             */
            setCalendarTitleInfo(year, month);
            //当月直接返回
            if (nowMonth.equals(TimeUtils.getStrByNy(year, month))) {
                return;
            }
            nowMonth = TimeUtils.getStrByNy(year, month);
            List<Calendar> calendars = calendarCache.get(nowMonth);
            if (calendars == null) {
                getBeforOrNextData();
            } else {
                changeMonthSus(cache.get(nowMonth));
            }
        });
        getFirstData();
    }

    /**
     * 设置 最近三个月份的信息
     * @param month
     */
    @SuppressLint("SetTextI18n")
    private void setCalendarTitleInfo(int year, int month) {
        tvNowMonth.setText(year + "年" + month + "月");
        if (month == 1) {
            tvBrfoeMonth.setText("12月");
            tvNextMonth.setText(month + 1 + "月");
        } else if (month == 12) {
            tvBrfoeMonth.setText(month - 1 + "月");
            tvNextMonth.setText("1月");
        } else {
            tvNextMonth.setText(month + 1 + "月");
            tvBrfoeMonth.setText(month - 1 + "月");
        }
    }

    /**
     * 获取数据成功-给view设置数据
     */
    private void setViewInfo(StudentCheckEntity data) {
        setNumInfo(data);
        mCalendarView.setSchemeDate(calendarCache.get(nowMonth));
        Calendar calendar = mCalendarView.getSelectedCalendar();
        nowDay = TimeUtils.getStrByNyr(calendar.getYear(), calendar.getMonth(), calendar.getDay());
        showDayDate(nowDay);
    }

    /**
     * 切换月份成功
     **/
    private void changeMonthSus(StudentCheckEntity data) {
        setNumInfo(data);
        mCalendarView.setSchemeDate(calendarCache.get(nowMonth));
        Calendar calendar = mCalendarView.getSelectedCalendar();
        //选择的日期是否属于切换后的天数
        boolean isInMonth = nowMonth.equals(TimeUtils.getStrByNy(calendar.getYear(), calendar.getMonth()));
        //选中的天数
        String choseDay = TimeUtils.getStrByNyr(calendar.getYear(), calendar.getMonth(), calendar.getDay());

        if (isInMonth) {
            showDayDate(choseDay);

        } else {
            stateLayoutRecyc.showEmptyView();
        }
    }


    /**
     * 显示一天的打卡记录
     *
     * @param day
     */
    private void showDayDate(String day) {
        StudentCheckEntity.ListBean dkList = historyCache.get(nowDay);
        if (dkList != null) {
            historyEntityList.clear();
            historyEntityList.add(dkList);
            adapter.notifyDataSetChanged();
            stateLayoutRecyc.showContentView();
        } else {
            stateLayoutRecyc.showEmptyView();
        }
    }



    /**
     * 前一个月-先在缓存里读取
     * 请求数据-切换日历视图-成功更新当前月份
     */
    @OnClick(R.id.layout_befor)
    public void onLayoutBeforClicked() {

        mCalendarView.scrollToPre(true);

    }

    /**
     * 下一个月
     */
    @OnClick(R.id.layout_next)
    public void onLayoutNextClicked() {
        mCalendarView.scrollToNext(true);
    }


    /**
     * 获取上一个或者下一个月的数据
     */
    private void getBeforOrNextData() {
        HttpHeper.get().parentService()
                .studentCheck(nowMonth,stuId)
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .map(data -> {
                    if (HttpConfig.RESPONSE_OK.equals(data.getStatus())) {
                        doDkData(data.getData(), nowMonth);
                    }
                    return data;
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonCallBack<StudentCheckEntity>(true, this) {
                    /**
                     * 切换月份成功
                     * @param data
                     */
                    public void onCallBackSuccess(StudentCheckEntity data) {
                        changeMonthSus(data);
                    }
                });
    }

    /**
     * 初始化时获取当月数据
     */
    private void getFirstData() {
        HttpHeper.get().parentService()
                .studentCheck(nowMonth,stuId)
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .map(data -> {
                    if (HttpConfig.RESPONSE_OK.equals(data.getStatus())) {
                        doDkData(data.getData(), nowMonth);
                    }
                    return data;
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonCallBack<StudentCheckEntity>(false, this) {
                    /**
                     * 请求成功缓存数据-更新数据
                     * @param data
                     */
                    public void onCallBackSuccess(StudentCheckEntity data) {
                        setViewInfo(data);
                        stateLayout.showContentView();
                    }

                    @Override
                    public void onFail(String mes) {
                        super.onFail(mes);
                        stateLayout.showErrorView();
                    }
                });
    }

    /**
     * 子线程处理数据
     * @param entity
     */
    private void doDkData(StudentCheckEntity entity, String monthStr) {

        List<Calendar> schemes = new ArrayList<>();
        //遍历每一天的打卡记录
        for (StudentCheckEntity.ListBean monthData : entity.getList()) {
            int[] nyr = TimeUtils.getStrYyr(monthData.getDates());
            if (monthData.getName() != null && !monthData.getName().isEmpty()) {
                int color;
                if (monthData.isCd()){
                    color = Color.parseColor("#ff6953");
                }else if (monthData.isQj()){
                    color = Color.parseColor("#fed504");
                }else {
                    color = Color.parseColor("#0087fc");
                }
                schemes.add(getSchemeCalendar(nyr[0], nyr[1], nyr[2], color));
                historyCache.put(monthData.getDates(),monthData);
            }
        }
        cache.put(monthStr, entity);
        calendarCache.put(monthStr, schemes);
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.addScheme(new Calendar.Scheme());
        return calendar;
    }

    /**
     * 设置天数 数据
     *
     * @param data
     */
    private void setNumInfo(StudentCheckEntity data) {
        tvStateZc.setText("正常：" + data.getNormal()+"天");
        tvStateQj.setText("请假：" + data.getLeave()+"天");
        tvStateYc.setText("迟到：" + data.getBeLate()+"天");
    }
}
